package cn.regexp.web.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.regexp.domain.ShopOrder;
import cn.regexp.domain.ShopOrderGoods;
import cn.regexp.domain.ShopUser;
import cn.regexp.mapper.OrderGoodsMapper;
import cn.regexp.mapper.OrderMapper;
import cn.regexp.redis.service.IShopUserRedisService;
import cn.regexp.service.IOrderService;
import cn.regexp.util.ApiBaseAction;
import cn.regexp.utils.CharUtil;
import cn.regexp.utils.JsonResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@RestController
@RequestMapping("pays")
public class PayController extends ApiBaseAction {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private IShopUserRedisService userRedisService;

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.mchId}")
    private String mchId;
    @Value("${wx.notifyUrl}")
    private String notifyUrl;
    @Value("${wx.jsApiOrderUrl}")
    private String jsApiOrderUrl;


    /**
     * 获取支付的请求参数
     */
    @ApiOperation(value = "获取支付的请求参数")
    @PostMapping("/prepay")
    public JsonResult<String> prepay(HttpServletRequest request, @RequestBody Long orderId) {
        // 获取 token
        String token = request.getHeader("token");
        // 获取用户
        ShopUser user = userRedisService.getUserByToken(token);
        // 获取订单
        ShopOrder order = orderMapper.selectById(orderId);
        if (ObjectUtil.isEmpty(order)) {
            return JsonResult.error(800001, "不存在该订单！", null);
        }
        if (ShopOrder.PAY_ACCOUNT_PAID.equals(order.getPayState())) {
            return JsonResult.error(80002, "该订单已支付！", null);
        }
        try {
            Map<Object, Object> params = new TreeMap<>();
            // 应用 ID
            params.put("appid", appId);
            // 商家账号
            params.put("mch_id", mchId);
            // 商品描述
            params.put("description", getOrderGoodsBody(orderId));
            // 商户订单编号
            params.put("out_trade_no", order.getOrderSn());
            // 回调地址
            params.put("notify_url", notifyUrl);
            Map<String, Object> amount = new HashMap<>();
            // 总金额
            amount.put("total", order.getGoodsPrice().multiply(new BigDecimal(100)).intValue());
            // 订单金额
            params.put("amount", amount);
            Map<String, Object> payer = new HashMap<>();
            // 用户标识
            payer.put("openid", user.getWeixinOpenId());
            // 支付者
            params.put("payer", payer);

            RestTemplate template = new RestTemplate();
            // 预支付交易会话标识
            String result = template.postForObject(jsApiOrderUrl, JSON.toJSONString(params), String.class);

            // 随机字符串
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            params.put("nonce_str", randomStr);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private String getOrderGoodsBody(Long orderId) {
        // 查询订单的所有商品
        QueryWrapper<ShopOrderGoods> wrapper = Wrappers.query();
        wrapper.eq("order_id", orderId);
        List<ShopOrderGoods> shopOrderGoods = orderGoodsMapper.selectList(wrapper);
        StringBuilder sb = new StringBuilder();
        sb.append("饭点到-");
        if (ObjectUtil.isNotEmpty(shopOrderGoods)) {
            shopOrderGoods.forEach(item -> sb.append(item.getGoodsName()).append("、"));
        }
        return sb.substring(0, sb.length() - 1);
    }

    @Autowired
    private IOrderService orderService;

    @ApiOperation(value = "订单支付")
    @PostMapping("/continuePay")
    public JsonResult<String> continuePay(@RequestBody String orderSn) {
        UpdateWrapper<ShopOrder> wrapper = new UpdateWrapper<>();
        wrapper.set("order_state", ShopOrder.ORDER_NOT_SEND)
                .set("pay_state", ShopOrder.PAY_ACCOUNT_PAID)
                .set("pay_time", DateUtil.date())
                .eq("order_sn", orderSn);
        orderService.update(wrapper);
        return JsonResult.success();
    }

}
